package com.example.util;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class RandomValidateCode {
    private final String randString = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 去掉了容易混淆的字符
    private final int width = 100;
    private final int height = 30;
    private final int lineCount = 6;
    private final Random random = new Random();

    public void getRandcode(HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
        // 1. 创建内存图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 2. 绘制背景和干扰线
        Graphics2D g = image.createGraphics();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        drawLines(g);

        // 3. 生成随机字符串
        String captcha = generateCaptcha(g);

        // 4. 存入Session（统一使用小写key）
        HttpSession session = request.getSession();
        session.setAttribute("verifycode", captcha.toLowerCase()); // 统一转小写存储

        // 5. 输出图像
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache, no-store");
        ImageIO.write(image, "JPEG", response.getOutputStream());
        g.dispose();
    }

    private String generateCaptcha(Graphics2D g) {
        StringBuilder sb = new StringBuilder();
        g.setFont(new Font("Arial", Font.BOLD, 22));

        for (int i = 0; i < 4; i++) {
            String ch = String.valueOf(randString.charAt(random.nextInt(randString.length())));
            sb.append(ch);
            g.setColor(new Color(20 + random.nextInt(110),
                    20 + random.nextInt(110),
                    20 + random.nextInt(110)));
            g.drawString(ch, 20 * i + 10, 22);
        }
        return sb.toString();
    }

    private void drawLines(Graphics2D g) {
        for (int i = 0; i < lineCount; i++) {
            g.setColor(getRandColor(160, 200));
            g.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }
    }

    private Color getRandColor(int fc, int bc) {
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}